#include "gifthread.h"
#include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QString>
#include <QDebug>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QFile>
#include <QMouseEvent>
#include <QPainterPath>
#include <QPainter>
#include <QMovie>

LoginWindow::LoginWindow(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::LoginWindow)
{
    ui->setupUi(this);

    // 渲染窗口
    setQssStyle(QString("../style/LoginStyle.qss"),this);

    // 初始化控件
    initControl();
    // 初始化信号槽
    initSignalSlot();

}

LoginWindow::~LoginWindow()
{
    qDebug()<<"登录窗口析构";
    delete ui;
}


void LoginWindow::initControl()
{
    // 注册、忘记密码、手机验证登录窗口初始化
    register_window = new RegisterWindow();
    forgetpwd_window = new ForgetPwdWindow();

    //设置close()释放对象内存,不设置的话只会hide()
    this->setAttribute(Qt::WA_DeleteOnClose);
    // 设置窗口背景透明
    //    setAttribute(Qt::WA_TranslucentBackground, true);//设置窗口背景透明
    // 设置无边框窗口
    this->setWindowFlags(Qt::FramelessWindowHint);
    // 设置窗口透明度
    // this->setWindowOpacity(0.95);

    // 固定窗口大小
    this->setFixedSize(QSize(500,370));

    QAction* action_user = new QAction(ui->le_user);
    action_user->setIcon(QIcon(":/prefix2/software/user.png"));
    ui->le_user->addAction(action_user,QLineEdit::LeadingPosition);

    QAction* action_password = new QAction(ui->le_pwd);
    action_password->setIcon(QIcon(":/prefix2/software/password.png"));
    ui->le_pwd->addAction(action_password,QLineEdit::LeadingPosition);

    // 为Label安装事件过滤器,点击事件，悬浮样式等
    ui->lab_register->installEventFilter(this);
    ui->lab_forgetpwd->installEventFilter(this);

    // 设置默认的头像
    QString head_url = QString("%1/%2").arg(PATH_IMG).arg("man.png");
    int borderWidth = 8; // 边框的宽度
    cv::Scalar borderColor(0, 0, 0, 255);
    ui->lab_logo->setPixmap(RoundBorderPixmap(downLoadFromUrl(head_url),borderWidth,borderColor));

}

void LoginWindow::initSignalSlot()
{
    connect(this,&QDialog::accepted,this,[=]{
        emit login_success();
    });

    connect(this,&QDialog::rejected,this,[=]{
        t1->quit();
        t1->wait();
        ui->stackedWidget->setCurrentWidget(ui->page_login);
        QMessageBox msgbox(QMessageBox::Information,"DragonIM","DD号或密码错误!",QMessageBox::Ok);
        msgbox.exec();

    });

    connect(this,&QDialog::finished,this,[=](int result){
        switch (result) {
        case 2:{
            QMessageBox msgbox(QMessageBox::Information,"DragonIM","用户已在其他设备登录!",QMessageBox::Ok);
            msgbox.exec();
            break;
        }
       }
    });


    connect(register_window,QOverload<int>::of(&RegisterWindow::sig_login_show),this,[=](int id){
        register_window->close();
        this->myShow(id);
    });

}

void LoginWindow::myShow(int id)
{
    ui->le_user->setText(QString::number(id));
}

void LoginWindow::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    // QDialog 默认窗口关闭调用 QDialog::reject();
    QDialog::done(3);
}

bool LoginWindow::eventFilter(QObject *object, QEvent *event)
{
    // 检查事件是否发生在我们的QLabel上
    if (object == ui->lab_register)
    {
        // 检查事件类型
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent* ev = static_cast<QMouseEvent*>(event);
            if(ev->button() == Qt::LeftButton){
                register_window->show();
            }
            // 你可以选择是否阻止事件进一步传播
            return true; // 返回true表示事件已被处理
        }
    }else if(object == ui->lab_forgetpwd){
        // 检查事件类型
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent* ev = static_cast<QMouseEvent*>(event);
            if(ev->button() == Qt::LeftButton){
                forgetpwd_window->Show();
            }
            // 你可以选择是否阻止事件进一步传播
            return true; // 返回true表示事件已被处理
        }
    }


    // 对于其他事件或对象，不处理并继续传递事件
    return QObject::eventFilter(object, event);
}

void LoginWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        // 记录鼠标按下的位置
        dragPosition = event->pos();
        isDragging = true;
    }
}

void LoginWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (isDragging && (event->buttons() & Qt::LeftButton)) {
        // 计算窗口的新位置
        int dx = event->x() - dragPosition.x();
        int dy = event->y() - dragPosition.y();
        move(x() + dx, y() + dy);
    }
}

void LoginWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        isDragging = false;
    }
}

void LoginWindow::on_btn_login_clicked()
{
    //获取用户名和密码
    QString user = ui->le_user->text();
    QString pwd = ui->le_pwd->text();

    //封装登录请求
    QVariantMap map;
    map["cmd"]="login";
    map["user"]=user.toInt();
    map["password"]=pwd;

    //发送登录请求
    GlobalObject::getGlobalObject()->sendRequest(map);

    qDebug()<<"主线程id:"<<QThread::currentThreadId();
    // 切换到登录动画界面
    ui->stackedWidget->setCurrentWidget(ui->page_wait);

    t1 = new GifThread(":/gif/software/wait.gif");
    t1->label = ui->lab_gif;
    t1->start();  

}

RegisterWindow *LoginWindow::getRegister_window() const
{
    return register_window;
}

void LoginWindow::on_btn_close_clicked()
{
    this->close();
}


void LoginWindow::on_le_user_editingFinished()
{
    // 在没有设置 validator() 验证器的情况下, 按下Enter 或 LineEdit失去焦点 发出editingFinished信号(前提是内容发生了改变)
    //获取用户名
    QString user = ui->le_user->text();

    QString head_url = QString("%1/%2.png").arg(PATH_IMG).arg(user);
    QPixmap head = downLoadFromUrl(head_url);

    // 用户名不正确，下载资源就是空的，什么也不做
    if(head.isNull())
        return;

    int borderWidth = 8; // 边框的宽度
    cv::Scalar borderColor(0, 0, 0, 255);
    ui->lab_logo->setPixmap(RoundBorderPixmap(PixmapToRoundOpenCV(downLoadFromUrl(head_url)),borderWidth,borderColor));

}


void LoginWindow::on_btn_min_clicked()
{
    this->showMinimized();
}

GifThread *LoginWindow::getT1() const
{
    return t1;
}



